package com.hqd.ch03.v51.boot.availability;

import com.hqd.ch03.v51.context.ApplicationContext;
import com.hqd.ch03.v51.context.ApplicationEventPublisher;
import com.hqd.ch03.v51.context.PayloadApplicationEvent;
import com.hqd.ch03.v51.core.ResolvableType;

public class AvailabilityChangeEvent<S extends AvailabilityState> extends PayloadApplicationEvent<S> {

    /**
     * Create a new {@link AvailabilityChangeEvent} instance.
     *
     * @param source the source of the event
     * @param state  the availability state (never {@code null})
     */
    public AvailabilityChangeEvent(Object source, S state) {
        super(source, state);
    }

    /**
     * Convenience method that can be used to publish an {@link AvailabilityChangeEvent}
     * to the given application context.
     *
     * @param <S>     the availability state type
     * @param context the context used to publish the event
     * @param state   the changed availability state
     */
    public static <S extends AvailabilityState> void publish(ApplicationContext context, S state) {
        publish(context, context, state);
    }

    /**
     * Convenience method that can be used to publish an {@link AvailabilityChangeEvent}
     * to the given application context.
     *
     * @param <S>       the availability state type
     * @param publisher the publisher used to publish the event
     * @param source    the source of the event
     * @param state     the changed availability state
     */
    public static <S extends AvailabilityState> void publish(ApplicationEventPublisher publisher, Object source,
                                                             S state) {
        publisher.publishEvent(new AvailabilityChangeEvent<>(source, state));
    }

    /**
     * Return the changed availability state.
     *
     * @return the availability state
     */
    public S getState() {
        return getPayload();
    }

    @Override
    public ResolvableType getResolvableType() {
        return ResolvableType.forClassWithGenerics(getClass(), getStateType());
    }

    private Class<?> getStateType() {
        S state = getState();
        if (state instanceof Enum) {
            return ((Enum<?>) state).getDeclaringClass();
        }
        return state.getClass();
    }

}
